package com.example.liwushuo.fragment;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.example.liwushuo.BaseApp;
import com.example.liwushuo.HomeListItemActivity;
import com.example.liwushuo.R;
import com.example.liwushuo.adapter.SelectionAdapter;
import com.example.liwushuo.bean.BaseHome;
import com.example.liwushuo.bean.HomeItem;
import com.example.liwushuo.urls.urls;
import com.example.liwushuo.utils.Utils;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class Gift extends Fragment implements OnItemClickListener {

	private int id;
	private PullToRefreshListView listView;
	private SelectionAdapter adapter;
	private List<HomeItem> list;
	private String url;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		id = getArguments().getInt("id");
		url = urls.getHomeUrl(id, Utils.getParams(getActivity(), "gender"),
				Utils.getParams(getActivity(), "generation"));
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_selection, null);
		listView = (PullToRefreshListView) view
				.findViewById(R.id.selection_listView);
		list = new ArrayList<HomeItem>();
		adapter = new SelectionAdapter(getActivity(), list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
		initData();
		return view;
	}

	private void initData() {

		BaseApp.getHttpUtils().send(HttpMethod.GET, url,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
					}

					@Override
					public void onSuccess(ResponseInfo<String> response) {
						String json = response.result;
						BaseHome baseHome = JSONObject.parseObject(json,
								BaseHome.class);
						if ("OK".equals(baseHome.getMessage())) {
							list.addAll(baseHome.getData().getItems());
							adapter.notifyDataSetChanged();
						}
					}
				});
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {

		Intent intent = new Intent(getActivity(), HomeListItemActivity.class);
		intent.putExtra("id", list.get(position -1).getId());
		startActivity(intent);

	}
}
